package tech.gismap.admin.web;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import tech.gismap.common.core.domain.R;
import tech.gismap.common.core.domain.model.LoginBody;
import tech.gismap.common.core.domain.model.RegisterBody;
import tech.gismap.common.core.utils.ValidatorUtils;
import tech.gismap.common.encrypt.annotation.ApiEncrypt;
import tech.gismap.common.json.utils.JsonUtils;
import tech.gismap.common.satoken.utils.LoginHelper;
import tech.gismap.common.sse.dto.SseMessageDto;
import tech.gismap.common.sse.utils.SseMessageUtils;
import tech.gismap.admin.web.vo.LoginVo;
import tech.gismap.admin.service.AuthStrategy;
import tech.gismap.admin.service.SysLoginService;
import tech.gismap.admin.service.SysRegisterService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 认证
 *
 * @author Lion Li
 */
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

    private final SysLoginService loginService;
    private final SysRegisterService registerService;
    private final ScheduledExecutorService scheduledExecutorService;


    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiEncrypt
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        assert loginBody != null;
        LoginVo loginVo = AuthStrategy.login(body, loginBody.getGrantType());
        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            SseMessageDto dto = new SseMessageDto();
            dto.setMessage("欢迎登录后台管理系统");
            dto.setUserIds(List.of(userId));
            SseMessageUtils.publishMessage(dto);
        }, 5, TimeUnit.SECONDS);
        return R.ok(loginVo);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 用户注册
     */
    @ApiEncrypt
    @PostMapping("/register")
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
        registerService.register(user);
        return R.ok();
    }
}
